#!/usr/bin/env python
import logging
import sys

import kopano

"""
synchronize permissions to archive stores

"""

ROLE_REVIEWER = ['folder_visible', 'read_items']

def logger(options):
    logging.basicConfig(stream=sys.stdout, level=options.loglevel)
    return logging.getLogger('aclset')

def main():
    parser = kopano.parser('spkul')
    options, args = parser.parse_args()
    log = logger(options)
    stats = {'users': 0, 'errors': 0}
    server = kopano.Server(options=options)

    for user in server.users():
        with kopano.log_exc(log, stats):
            log.info('processing user %s', user.name)
            stats['users'] += 1

            archive_store, archive_folder = user.archive_store, user.archive_folder

            if archive_store:
                log.debug('syncing permissions')

                # for the user store, copy rights (masked to ROLE_REVIEWER)
                for p in user.store.permissions():
                    rights = [r for r in p.rights if r in ROLE_REVIEWER]
                    archive_folder.permission(p.member, create=True).rights = rights
                archive_folder.permission(kopano.Group('Everyone'), create=True).rights = []

                # if archiving to subfolder, copy store rights to subtree, adding 'folder_visible'
                if archive_folder is not archive_store.subtree:
                    for p in user.store.permissions():
                        pa = archive_store.subtree.permission(p.member, create=True)
                        pa.rights = [r for r in pa.rights if r != 'folder_visible'] + ['folder_visible']

                # for each folder, copy rights (masked to ROLE_REVIEWER)
                for folder in user.folders():
                    archive_folder = folder.archive_folder
                    if archive_folder:
                        for p in folder.permissions():
                            rights = [r for r in p.rights if r in ROLE_REVIEWER]
                            archive_folder.permission(p.member, create=True).rights = rights

            else:
                log.debug('user has no archive store')

if __name__ == '__main__':
    main()
